package com.gainloop;

import java.io.IOException;
import java.net.MalformedURLException;

import org.alexd.jsonrpc.JSONRPCException;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.android.Facebook.DialogListener;
import com.gainloop.Api.Auth;
import com.gainloop.Api.Entity.Session;
import com.gainloop.Api.Entity.User;
import com.gainloop.Data.Registry;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class Login extends ActivityAbstract{
	public static final String APP_ID = "184501141565634";
	Facebook facebook = new Facebook(APP_ID);
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(!isOnline()){
			Log.v("User is not connected","");
			alertNoConn();
			return;
		}
		
		Registry.Init(this);

        setContentView(R.layout.login);
        initHeader();
		headerTitle.setText(R.string.login);
		
		Session session = Registry.GetSession();
		if(session != null) {
			Log.v("session", "session found on the registry");
			Auth auth = Auth.getInstance();
			
			try {
				User user = auth.getUser(session);
				
				if(user != null) {
					Log.v("session", "user found from session registry");
					Registry.SetUser(user);
					goToHome();
					return;
				}
				
			} catch (JSONRPCException e) {
				e.printStackTrace();
				Registry.SetSession(null);
			}
		}

		FbAuth();
	}
	
	
	private void goToHome() {
		Intent intent=new Intent(Login.this,Home.class);
		Login.this.startActivity(intent);
		finish();
	}

	/**
	 * This will handle the initial FaceBook login.
	 */
	private void FbAuth() {
		facebook.authorize(this,new String[] { "email","read_friendlists"}, new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
				
            	String response = null;
            	long fbId = 0;
 
            	try {
            		//Get the user profile info to a string object.
            		response = facebook.request("me");
				} catch (MalformedURLException e) {
					e.printStackTrace();
					throw new RuntimeException("web error");
				} catch (IOException e) {
					e.printStackTrace();
					throw new RuntimeException("facebook data error");
				}
				
				JSONObject json=null;
				try {
					//it is a JSON object , so we need to parse it to take what we need...
					json = Util.parseJson(response);	
				} catch (JSONException e) {
					e.printStackTrace();
					throw new RuntimeException("json login error");
				} catch (FacebookError e) {
					e.printStackTrace();
					throw new RuntimeException("facebook error");
				}
				
				try {
					fbId = Long.parseLong(json.getString("id"));
				} catch (JSONException e1) {
					e1.printStackTrace();
					throw new RuntimeException("server side error");//fatal error - Meir
				}	
				
				try {
					int res = Auth.getInstance().signInFb(fbId, facebook.getAccessToken());
					if(res != 0) {
						throw new RuntimeException("server sign in error");
					}
				} catch (JSONRPCException e1) {
					e1.printStackTrace();
					throw new RuntimeException("sign in error");
				}
				
				goToHome();
            }

			@Override
            public void onFacebookError(FacebookError error) {
				Toast toast = Toast.makeText(Login.this, "Facebook has encountered an error on login!, please try again later...", Toast.LENGTH_LONG);
        		toast.show();
        		error.printStackTrace();
        		Log.d("error","onFacebookError");
			} 

            @Override
            public void onError(DialogError e) {
            	//Toast toast = Toast.makeText(Login.this, "Make Sure that you are connected to the Internet Before entering this App!", Toast.LENGTH_LONG);
            	Toast toast = Toast.makeText(Login.this, "Facebook has encountered an error on login! please try again later...", Toast.LENGTH_LONG);
        		//toast.show();
            	//alertNoConn();//TODO - need to test this...
        		Log.d("error","onError");
        		e.printStackTrace();
        		throw new RuntimeException("FaceBook Dialog Error");
            }

            

			@Override
            public void onCancel() {
            	Toast toast = Toast.makeText(Login.this, "You must login to Facebook to use this App!", Toast.LENGTH_SHORT);
        		toast.show();
        		Log.d("error","onCancel");
            	FbAuth();
            }
        });	
	}
	
	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        facebook.authorizeCallback(requestCode, resultCode, data);
    }
	
	private void alertNoConn() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Make Sure that you are connected to the Internet Before entering this App!")
		       .setCancelable(true).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	                Login.this.finish();
	           }
	    });

		AlertDialog alert = builder.create();
		alert.show();
	}
	
	public boolean isOnline() {
		 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		 if(cm==null){
			 return false;
		 }
		 NetworkInfo netInfo = cm.getActiveNetworkInfo();
		 if(netInfo==null){
			 return false;
		 }
		 return netInfo.isConnected();
	}

}
